#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'hhuua'

import aiomysql
import logging
from db_pool import get_mysql_pool
logging.basicConfig(level=logging.ERROR)


def log(sql):
    logging.info('SQL: %s' % sql)


async def select(pool, sql, args, size=None):
    with (await pool) as conn:
        cur = await conn.cursor(aiomysql.DictCursor)
        sql = sql.replace('?', '%s')
        await cur.execute(sql, tuple(args) or ())
        if size:
            values = await cur.fetchmany(size)
        else:
            values = await cur.fetchall()
        await cur.close()
        logging.info('select fet size: %s' % len(values))

        return values


async def execute(pool, sql, args, autocommit=True):
    async with pool.get() as conn:
        if not autocommit:
            await conn.begin()
        try:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                sql = sql.replace('?', '%s')
                await cur.execute(sql, tuple(args) or ())
                affected = cur.rowcount
            if not autocommit:
                await conn.commit()
        except BaseException as e:
            logging.warning(repr(e))
            if not autocommit:
                await conn.rollback()
            raise
        return affected


def create_args_string(num):
    L = []
    for n in range(num):
        L.append('?')
    return ', '.join(L)

# ORM


# Model元类
class ModelMetaclass(type):
    def __new__(cls, name, bases, attrs):
        # 排除Model类本身:
        if name == 'Model':
            return type.__new__(cls, name, bases, attrs)
        else:
            # 获取table名称
            tableName = attrs.get('__table__', None) or name
            logging.info('found model: %s (table: %s)' % (name, tableName))
            # 获取所有的Field和主键名:
            mappings = dict()
            fields = []
            primaryKey = None
            # 遍历所有属性,找出Field类,并将这些属性保存在mappins中,并从attrs中移除
            for k, v in attrs.items():
                if isinstance(v, Field):
                    logging.info('Model:%s found Field: %s ==> %s' % (name, k, v))
                    mappings[k] = v
                    # 是否是主键
                    if v.primary_key:
                        # 找到主键:
                        if primaryKey:
                            # 主键重复
                            raise RuntimeError('Model:%s 主键重复: %s' % (name, k))
                        # 设置主键key值
                        primaryKey = k
                    else:
                        fields.append(k)
            # if not primaryKey:
            #     raise RuntimeError('Model:%s 没有主键' % name)

            # 将已经保存到mappings的值从attrs中移除
            for k in mappings.keys():
                attrs.pop(k)

            # 所有非主键的值
            escaped_fields = list(map(lambda f: '`%s`' % f, fields))
            # 保存属性和列的映射关系到__mappings__
            attrs['__mappings__'] = mappings
            attrs['__table__'] = tableName
            attrs['__primary_key__'] = primaryKey  # 主键属性名
            attrs['__fields__'] = fields  # 除主键外的属性名

            # 构造默认的SELECT, INSERT, UPDATE和DELETE语句:
            attrs['__select__'] = 'select %s from `%s`' % (', '.join(escaped_fields), tableName)

            attrs['__insert__'] = 'insert into `%s` (%s) values (%s)' % (
                tableName, ', '.join(escaped_fields), create_args_string(len(escaped_fields)))

            attrs['__update__'] = 'update `%s` set %s where `%s`=?' % (
                tableName, ', '.join(map(lambda f: '`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey)

            attrs['__delete__'] = 'delete from `%s` where `%s`=?' % (tableName, primaryKey)
            return type.__new__(cls, name, bases, attrs)


# Model为ORM对象的基类,元类为:ModelMetaclass
class Model(dict, metaclass=ModelMetaclass):
    pool = None

    # 使用可变参数来让属性填写变的简单
    def __init__(self, **kw):
        super(Model, self).__init__(**kw)

    # 实现get,set,使Model类即可以向其父类dict使用key值访问m,也可以使用点语法进行访问
    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r'Model obj has no attribut:%s' % key)

    def __setattr__(self, key, value):
        self[key] = value

    def getValues(self, key):
        return getattr(self, key, None)

    def getValueOrDefault(self, key):
        value = getattr(self, key, None)
        if value is None:
            field = self.__mappings__[key]
            # 寻找在__mappings__中有没有设置默认值
            if field.default is not None:
                value = field.default() if callable(field.default) else field.default
                logging.info('using default value for %s: %s' % (key, str(value)))
                # 将默认值进行赋值
                setattr(self, key, value)
        return value

    @classmethod
    async def find_all(cls, where=None, args=None, **kw):
        sql = [cls.__select__]
        if where:
            sql.append('where')
            sql.append(where)
        if args is None:
            args = []

        group_by = kw.get('groupBy', None)
        if group_by:
            sql.append('group by')
            sql.append(group_by)

        order_by = kw.get('orderBy', None)
        if order_by:
            sql.append('order by')
            sql.append(order_by)

        limit = kw.get('limit', None)
        if limit is not None:
            sql.append('limit')
            if isinstance(limit, int):
                sql.append('?')
                args.append(limit)
            elif isinstance(limit, tuple) and len(limit) == 2:
                sql.append('?,?')
                args.extend(limit)
            else:
                raise ValueError('Invalid limit value: %s' % str(limit))
        rs = await select(get_mysql_pool(), ' '.join(sql), args)
        return [cls(**r) for r in rs]

    # 实现数据库存的方法
    async def save(self):
        args = list(map(self.getValueOrDefault, self.__fields__))
        try:
            rows = await execute(get_mysql_pool(), self.__insert__, args)
            if rows != 1:
                logging.info('failed to insert record: affected rows: %s' % rows)
        except BaseException as e:
            logging.warning('存储错误: %s' % repr(e))

    # 实现数据库删除的方法
    async def removewithcolumn(self, column, value):
        rs = await execute(get_mysql_pool(), 'delete from `%s` where `%s`=?' % (self.__table__, column), [value])
        if rs != 1:
            logging.warning('failed to delete record: Column:%s Value:%s', column, str(value))

    # 根据主键值删除
    async def remove(self, pkvalue):
        rs = await execute(get_mysql_pool(), '%s' % self.__delete__, [pkvalue])
        if rs != 1:
            logging.warning('failed to delete __primary_key__:%s' % str(pkvalue))

    async def update(self, pkvalue):
        args = list(map(self.getValueOrDefault, self.__fields__))
        args.append(pkvalue)
        rs = await execute(get_mysql_pool(), '%s' % (self.__update__), args)
        if rs != 1:
            logging.warning('failed to update __primary_key__:%s' % str(pkvalue))


# Field类型基类
class Field(object):
    # name:列名称
    # column_type:列类型
    # primary_key:是否是主键
    # default:默认值
    def __init__(self, name, column_type, primary_key, default):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default

    # 输出
    def __str__(self):
        return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)


class StringField(Field):
    # 默认长度为100
    def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'):
        super(StringField, self).__init__(name, ddl, primary_key, default)


class IntegerField(Field):
    def __init__(self, name=None, primary_key=False, default=0):
        super().__init__(name, 'bigint', primary_key, default)


class BooleanField(Field):
    def __init__(self, name=None, default=False):
        super().__init__(name, 'boolean', False, default)


class FloatField(Field):
    def __init__(self, name=None, primary_key=False, default=0.0):
        super().__init__(name, 'real', primary_key, default)


class TextField(Field):
    def __init__(self, name=None, default=None):
        super().__init__(name, 'text', False, default)
